package com.aspire.wap.core.http;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

/**
 * @deprecated
 * @author Yoyo
 *
 */
public class SiChuanHttpUtils {

	public static final String MOBILE = "sc_cmnet_mobile";

	// 从cookie中获得值的方法，如果没有，就会返回null
	public static String getMobileFromCookie(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		String cookieValue = "";
		if (cookies == null) {
			return cookieValue;
		}
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			if (cookie.getName().equals(MOBILE)) {
				cookieValue = cookie.getValue();
				cookieValue = decryptString(cookieValue);
			}
		}

		return cookieValue;
	}

	private static final String CRYPT_KEY = "v3VC0LfGq4IL9KgIgKqZrQ1m";// 连调暂用密钥
	private static final String CRYPT_ALGORITHM = "DESede";

	private static String decrypt(String value) {// 解密
		try {
			SecretKeySpec keySpec = new SecretKeySpec(CRYPT_KEY.getBytes(),
					CRYPT_ALGORITHM);
			Cipher cipher = Cipher.getInstance(CRYPT_ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, keySpec);

			byte[] decodedByte = Base64.decodeBase64(value.getBytes());
			byte[] decryptedByte = cipher.doFinal(decodedByte);
			return new String(decryptedByte);
		} catch (Exception e) {
			return null;
		}
	}

	public static String decryptString(String str) {
//		String ganrao = RandomStringUtils.random(5, "abcdefgABCDEFG");
		return StringUtils.substring(decrypt(str), 5);
	}
}
